# This is example of config/initializers/sitemap_spider.rb file.

require 'sitemap_spider'

# Example of how to redefine the default callbacks.
# Here we want to dynamically change sitemap for Article and Category objects,
# Article objects only if they are active.
#
# Sitemaps.do takes at least two arguments:
# 1) sitemap config name (default is :main_sitemap, this is also an argument for updates_sitemap method)
# 2) symbol name of Sitemap class method to be called
# 3) any other arguments to the Sitemap class method

module SitemapSpider
  module SitemapBase
    module ClassMethods
      def updates_sitemap(sitemap_name = Sitemaps::DEFAULT_SITEMAP_NAME)
        after_create Callbacks.new(sitemap_name)
        before_update Callbacks.new(sitemap_name)
        before_destroy Callbacks.new(sitemap_name)
      end
    end
            
    class Callbacks
      def after_create(record)
        if (record.kind_of?(Article) and record.active) or record.kind_of?(Category)
          Sitemaps.do(@sitemap_name, :update_records, [record], nil)
        end
        true
      end

      def before_update(record)
        old_record = record.class.find(record)
        add_rec = (((record.kind_of?(Article) and record.active) or record.kind_of?(Category)) ? [record] : [])
        rem_rec = (((record.kind_of?(Article) and old_record.active) or record.kind_of?(Category)) ? [old_record] : [])

        # shortcut, we use only 'loc' now so don't bother to call Sitemaps.do if old loc and new loc are the same
        return true if ((add_rec[0] and rem_rec[0] and add_rec[0].loc == rem_rec[0].loc) or (not add_rec[0] and not rem_rec[0]))

        Sitemaps.do(@sitemap_name, :update_records, add_rec, rem_rec)
        true
      end

      # Delete record from a sitemap.
      def before_destroy(record)
        if (record.kind_of?(Article) and record.active) or record.kind_of?(Category)
          Sitemaps.do(@sitemap_name, :update_records, nil, [record])
        end
        true
      end
    end
  end
end

# config
SitemapSpider::Sitemaps.config({
  :output_file => 'public/sitemap.xml',
  :output_tmp_file => 'tmp/sitemap.xml.tmp',
  :add_only_valid => false,
  :debug => false,
  :errors_are_fatal => false,
  :print_totals => false,
  :produce_sitemap => true
})
